<template>
  <!--按钮-->
  <div>
    <el-button type="danger" :icon="Plus" @click="SaveBreedingSow">新增</el-button>
    <el-button type="danger" :icon="DocumentAdd">保存</el-button>
    <el-button type="danger" :icon="BottomRight">撤销</el-button>
    <el-button type="danger" :icon="Delete">删除</el-button>
  </div>

  <el-row style="margin-top: 20px;margin-bottom: 20px;">
        <el-col :span="5">
          <el-form-item label="负责人:">
            <el-select v-model="single.principal" placeholder="请选择" clearable>
              <el-option v-for="user in userList" :key="user.userId" :label="user.userMyName" :value="user.userMyName"  />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5" style="margin-left: 10px;">
          <el-form-item label="断奶日期:">
            <el-date-picker v-model="single.pregnancyTestDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择时间" :size="size" />
          </el-form-item>
        </el-col>
        <el-col :span="3" style="margin-left: 30px;margin-top: 3px;">单据号&nbsp;-- --</el-col>
        <el-col :span="3" style="margin-top: 3px;">流水号&nbsp;-- --</el-col>
    </el-row>
    <hr size="6" style="background-color:rgb(232.8, 233.4, 234.6)">
  <!--表格-->
  <table  class="show" style="margin-top: 20px;" border="1">
    <tr align="center">
      <td width="180">序号</td>
      <td width="180">耳号</td>
      <td width="180">哺乳天数</td>
      <td width="180">当前栋舍</td>
      <td width="180">当前栏位</td>
      <td width="180">转入栋舍</td>
      <td width="180">转入栏位</td>
      <td width="250">断奶只数(只)</td>
      <td width="300">断奶总窝重(公斤)</td>
      <td width="250">种母重量(公斤)</td>
    </tr>

    <tr v-for="(item, index) in form" :key="index">
      <!--序号-->
      <td width="180"><el-input :value="index + 1" /></td>
      <!--耳号-->
      <td width="150">
        <el-select v-model="item.basicInforId" placeholder="请选择" clearable @change="handlebedroomField(item.basicInforId,index)" >
          <el-option v-for="basic in basicInforList.filter((d:any) => d.gender == 2 && d.pigTypeId==2 && d.isYesFarrowing==2)" :key="basic.basicInforId" :label="basic.earNumber" :value="basic.basicInforId" @click="resultCheck(item.basicInforId,index)">
          </el-option>
        </el-select>
      </td>
      <!--哺乳天数 (当前日期-分娩日期)-->
      <td width="180">{{item.DateDay}}</td>
      <!--当前栏位-->
      <td width="180">{{item.currentbuilding}}</td>
      <!--当前栋舍-->
      <td width="180">{{item.currentfield}}</td>
      <!--转入栋舍-->
      <td width="150">
        <el-select v-model="item.bedroomId" placeholder="请选择" @change="handlefield(item.bedroomId, index)" clearable>
          <el-option v-for="bedroom in bedroomList" :key="bedroom.bedroomId" :label="bedroom.bedroomName" :value="bedroom.bedroomId" />
        </el-select>
      </td>
      <!--转入栏位-->
      <td width="180">
        <el-select v-model="item.fieldId" placeholder="请选择" clearable>
          <el-option v-for="field in fieldList[index]" :key="field.fieldId" :label="field.fieldName" :value="field.fieldId" />
        </el-select>
      </td>
      <!--断奶只数(只)-->
      <td width="150">
        <el-input v-model="item.ablactationNum" />
      </td>
      <!--断奶总窝重(公斤)-->
      <td width="180"><el-input v-model="item.ablactationSum" /></td>
      <!--种母重量(公斤)-->
      <td width="180"><el-input v-model="item.ablactationWeight" /></td>
    </tr>
  </table>
  <!--增行 删行-->
  <div>
    <el-button type="danger" link @click="addRow">+增行</el-button>
    <el-button type="danger" link @click="removeRow" :disabled="form.length <= 0">-删行</el-button>
  </div>

</template>

<script lang="ts" setup>
import { Plus, Delete, DocumentAdd, BottomRight } from '@element-plus/icons-vue'
import { ref, onMounted, reactive } from 'vue'
import axios from 'axios';
import { ElMessage } from 'element-plus';
import { useRouter, useRoute } from 'vue-router'

const apiUrl = import.meta.env.VITE_APP_API_URL;
const apiBedinUrl = import.meta.env.VITE_APPRead_API_URL;

//创建路由实例
const router = useRouter()
const route = useRoute()

const size = ref<'default' | 'large' | 'small'>('default')

//当前时间
const date = new Date();

//响应式数据 获取
const condition = reactive({
  pageIndex: 1,
  pageSize: 100,
  bedroomTypeId: 0,
  bedroomName: '',
  personName: ''
})

//断奶时间
const single=reactive({
    pregnancyTestDate:'',
    principal:'',
})

const form = reactive([{
      documentNumber: "",
      serialNumber: "",
      ablactationPro: "",
      ablactationTime: date.getFullYear()+'-'+(date.getMonth()+1).toString().padStart(2, '0')+'-'+ date.getDate().toString().padStart(2, '0'),
      basicInforId: "",
      ablactationWeight: "",
      ablactationNum: "",
      currentBuilding: "",
      currentfield: "",
      bedroomId: '',
      fieldId: '',
      ablactationSum: "",
      pregnancyTestDate:'',
      isDels: true,
      createdOwner: localStorage.getItem("userName"),
      createdTime:new Date(),
      updateOwner: '',
      updatedTime: null,
      examineOwner: '',
      examineTime: null,
      //断奶天数
      DateDay:''
}])

//增行
const addRow = () => {
  form.push({
    documentNumber: "",
      serialNumber: "",
      ablactationPro: "",
      ablactationTime: date.getFullYear()+'-'+(date.getMonth()+1).toString().padStart(2, '0')+'-'+ date.getDate().toString().padStart(2, '0'),
      basicInforId: "",
      ablactationWeight: "",
      ablactationNum: "",
      currentBuilding: "",
      currentfield: "",
      bedroomId: '',
      fieldId: '',
      ablactationSum: "",
      pregnancyTestDate:'',
      isDels: true,
      createdOwner: localStorage.getItem("userName"),
      createdTime:new Date(),
      updateOwner: '',
      updatedTime: null,
      examineOwner: '',
      examineTime: null,
       //断奶天数
      DateDay:''
  })
  console.log(form)
}
//删行
const removeRow = () => {
  if (form.length > 0) {
    form.pop()
  }
}

//新增
const SaveBreedingSow = () => {
  console.log(form)
  const obj = {
    ablactations: form
  }
  axios.post(apiUrl+'/api/Ablactations/addAblactations', obj)
  .then(res => {
    if (res.data.code == 0) {
      ElMessage.success("添加种母期初成功");
      router.push('/ShowAblactation')
    } else {
      ElMessage.error("添加种母期初失败");
    }
  })
}
//--------------下拉框---------------//

//获取负责人
const userList=ref([])
const handleprincipal=()=>{
    axios.post(apiUrl+'/api/Users/GetUsers',{
      pageIndex:1,
      pageSize:1000,
    })
    .then(res=>{
        userList.value=res.data.data.list
    })
}

//耳号
const basicInforList: any = ref([])
const handlebasicInfor = () => {
    axios.post(apiBedinUrl+'/api/Basics/SearchBasic', {})
    .then(res => {
        console.log(res.data.data)
        basicInforList.value = res.data.data
    })
}

//获取当前栋舍 栏位
const bedroomField:any = reactive({
  gender: '',
  currentbuilding: '',
  currentfield:'',
});
//将该方法放在耳号下拉框 变化的时候将id值与下标传过来了
const handlebedroomField = (id:number,index:number) => {
  axios.post(apiBedinUrl+"/api/Basics/SearchBedroomField", {
    //根据耳号id进行获取
    basicInforId:id
  }).then((res) => {
    console.log('栏位返填',res.data.data)
    //给栋舍 栏位 性别赋值
    bedroomField.gender=res.data.data.gender;
    bedroomField.currentbuilding=res.data.data.bedroomName;
    bedroomField.currentfield=res.data.data.fieldName;
    console.log(bedroomField.currentbuilding);
    //根据下标进行赋值
    form[index].currentbuilding=bedroomField.currentbuilding;
    form[index].currentfield=bedroomField.currentfield;
  });
};

//获取栋舍
const bedroomList: any = ref([])
const handleBedroom = () => {
  axios.post(apiUrl+'/api/BedRoom/ShowBedroom', {
    pageIndex: condition.pageIndex,
    pageSize: condition.pageSize,
    bedroomTypeId: condition.bedroomTypeId,
    bedroomName: condition.bedroomName,
    personName: condition.personName
  }).then(res => {
    bedroomList.value = res.data.data.list
  })
}

//获取栏位
const fieldList: any = ref([])
const handlefield = (id: number, index: number) => {
  form[index].fieldId = ''
  axios.post(apiUrl+'/api/BedRoom/GetBrdroomIdField', {
    bedroomId: id
  }).then(res => {
    fieldList.value[index] = res.data.data;
    console.log("栏位", fieldList.value[index], index);
  })
}

const page = reactive({
  basicInforId: '',
  bedroomId: '',
  turnBuilding: '',
  nestNumber: '',
  pageIndex: 1,
  pageSize: 3,
  totalCount: 0,
  pageCount: 0
})

//母猪分娩列表
const tableData = ref([])
const loadData = () => {
  axios.post(apiBedinUrl+'/api/Farrowings/ShowFarrowings', {
    basicInforId: page.basicInforId || 0,
    bedroomId: page.bedroomId || 0,
    turnBuilding: page.turnBuilding,
    nestNumber: page.nestNumber,
    pageIndex: page.pageIndex,
    pageSize: page.pageSize
  })
    .then(res => {
      console.log("母猪分娩列表", res.data.data.list);
      tableData.value = res.data.data.list;
      page.totalCount = res.data.data.totalCount;
      page.pageCount = res.data.data.pageCount;
    })
}

//断奶天数
const resultCheck=(id:number,index:number)=>{
  if(id!=0)
  {
    form[index].DateDay=Math.ceil((new Date(form.ablactationTime)-new Date(tableData.value.farrowingDate))/ (1000 * 3600 * 24))
    console.log("11111",form[index].DateDay);
  }
  else{
    form[index].DateDay=0;
  }
}

//创建生命周期函数钩
onMounted(() => {
  handlebasicInfor()
  handleBedroom();//获取栋舍
  handleprincipal();//负责人
  loadData();//分娩列表
})


</script>

<style>
.show {
  border-collapse: collapse;
  border-top: 2px solid red; /* 设置上边框为红色 */
}
</style>
